package com.ruoyi.backend.controller;

import com.github.pagehelper.PageInfo;
import com.ruoyi.backend.constant.InversionConstants;
import com.ruoyi.backend.dto.EcologicalDataDTO;
import com.ruoyi.backend.service.EcologicalService;
import com.ruoyi.backend.service.FileService;
import com.ruoyi.backend.vo.EcologicalDataVO;
import com.ruoyi.backend.vo.InversionResultVO;
import com.ruoyi.common.annotation.DataSource;
import com.ruoyi.common.core.domain.R;
import com.ruoyi.common.enums.DataSourceType;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.SecurityUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.SseEmitter;

import javax.validation.constraints.NotNull;
import java.time.Instant;
import java.util.ArrayList;

@RequestMapping("/backend/ecological")
@RestController("BackendEcologicalController")
@Api(tags = "生态参量数据管理相关接口")
public class EcologicalController {

    @Autowired
    private EcologicalService ecologicalService;

    @Autowired
    private FileService fileService;

    Logger logger = LoggerFactory.getLogger(EcologicalController.class);


    /**
     * 生态参量反演接口
     *
     * @param mineId          矿山ID
     * @param dateTime        时间
     * @param spatialCoverage 空间覆盖
     * @param is              是否高精度
     * @param ecologicalIds   参数ID
     * @return
     */

    @ApiOperation(value = "生态参量反演接口")
    @PostMapping(value = "/inversion")

    public R<String> inversion(@RequestParam String mineId,
                                @RequestParam String dateTime,
                                @RequestParam String spatialCoverage,
                                @RequestParam String is,
                                @RequestParam ArrayList<String> ecologicalIds) {

        SseEmitter sseEmitter = SseController.SseMap.getOrDefault(SecurityUtils.getLoginUser().getToken(), null);
        if (sseEmitter == null) return R.fail("请先进行连接");
        new Thread(() -> ecologicalService.inversion(mineId, dateTime, spatialCoverage, is, ecologicalIds,sseEmitter)).start();
        return R.ok("开始反演");
    }

    @DataSource(DataSourceType.SLAVE)
    @ApiOperation(value = "删除生态参量反演结果接口")
    @DeleteMapping("/deleteInversion")
    public R<String> deleteInversion(@RequestParam String fileName) {

        boolean deleteResult = fileService.deleteFile(InversionConstants.INVERSION_BUCKET_NAME, fileName);

        if (!deleteResult) {
            return R.fail("生态参量反演数据删除失败");
        }

        return R.ok("生态参量反演数据删除成功");
    }


    /**
     * 查询生态参量反演结果接口
     *
     * @param mineId       矿区ID
     * @param startDate    开始日期
     * @param endDate      结束日期
     * @param status       状态值
     * @param ecologicalId 生态ID
     * @param pageNumber    分页页号
     * @param pageSize      分页大小
     * @return 生态参量反演结果VO对象
     */
    @DataSource(DataSourceType.SLAVE)
    @ApiOperation(value = "查询生态参量反演结果接口")
    @GetMapping("/getInversion")
    public R<PageInfo<InversionResultVO>> getInversion(@RequestParam(required = false) String mineId,
                                                            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Instant startDate,
                                                            @RequestParam(required = false) @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) Instant endDate,
                                                            @RequestParam(required = false) Integer status,
                                                            @RequestParam(required = false) String ecologicalId,
                                                            @RequestParam int pageNumber,
                                                            @RequestParam int pageSize) {
        try {
            return R.ok(ecologicalService.searchInversionResult(mineId, startDate, endDate, status, ecologicalId,pageNumber,pageSize));
        } catch (Exception e) {
            logger.error(e.toString());
            return R.fail("查询结果失败，请联系管理员");
        }

    }


    /**
     * 保留反演结果接口
     *
     * @param fileName 文件名
     * @return
     */
    @DataSource(DataSourceType.SLAVE)
    @ApiOperation(value = "保留反演结果接口")
    @PutMapping("/saveInversion")
    public R<String> saveInversion(@RequestParam String fileName) {
        try {
            boolean result = ecologicalService.saveInversion(fileName);
            if (!result) {
                return R.fail("生态参量反演结果保留失败，请重试");
            }
        } catch (Exception e) {
            throw new ServiceException("生态参量反演结果保留失败");
        }
        return R.ok("生态参量反演结果保留成功");
    }

    @DataSource(DataSourceType.SLAVE)
    @ApiOperation(value = "海量数据(生态参量数据)查询接口")
    @GetMapping("/massiveData")
    public R<ArrayList<EcologicalDataVO>> getMassiveData(@RequestParam @NotNull String mineId,
                                                        @RequestParam @NotNull String ecologicalCategory
                                                        ){
        ArrayList<EcologicalDataVO> result = ecologicalService.selectMassiveEcologicalData(mineId,ecologicalCategory);
        return R.ok(result);
    }

    //生态参量数据上传接口
    @ApiOperation(value = "上传生态参量数据接口")
    @PostMapping("/uploadData")
    public R<String> uploadData(@RequestBody EcologicalDataDTO ecologicalDataDTO) {
        ecologicalService.uploadData(ecologicalDataDTO);
        return R.ok("数据上传成功");
    }

    //生态参量数据修改接口
    @ApiOperation(value = "修改生态参量数据接口")
    @PutMapping("/updateData")
    public R<String>updateData(@RequestBody EcologicalDataDTO ecologicalDataDTO) {
         ecologicalService.updateData(ecologicalDataDTO);
         return R.ok("数据修改成功");
    }

    //生态参量数据删除接口
    @ApiOperation(value = "删除生态参量数据接口")
    @DeleteMapping("/deleteData")
    public R<String>deleteData(@RequestParam @NotNull Long id){
        ecologicalService.deleteData(id);
        return  R.ok("数据删除成功");
    }
}
